package com.changgou.search.controller;

import com.changgou.search.feign.SkuFeign;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Controller
@RequestMapping(value = "/search")
public class SkuController {

    @Autowired
    private SkuFeign skuFeign;

    /**
     * 搜索
     * @param searchMap
     * @return
     */
    @GetMapping(value = "/list")
    public String search(@RequestParam(required = false) Map<String,String> searchMap, Model model){
        //调用changgou-service-search微服务
        Map<String,Object> resultMap = skuFeign.search(searchMap);
        //搜索数据结果
        model.addAttribute("result",resultMap);
        //搜索条件
        model.addAttribute("searchMap",searchMap);
        //请求地址
        String[] url = url(searchMap);
        model.addAttribute("url",url);
        return "search";
    }
    /*
    * URL组装和处理
    * */
    private String[] url(Map<String, String> searchMap) {// { spec_网络:"移动4G","keywords":"华为"}
        String url = "/search/list"; // a/b?id=1&
        String sorturl = "/search/list";
        if (searchMap != null && searchMap.size()>0) {
            url += "?";
            sorturl += "?";
            for (Map.Entry<String, String> entry : searchMap.entrySet()) {
                //如果是排序 则 跳过 拼接排序的地址 因为有数据
                if(entry.getKey().equalsIgnoreCase("pageNum")){
                    continue;
                }
            }
            url = url.substring(0,url.length()-1);
            sorturl=sorturl.substring(0,sorturl.length()-1);
        }
        return new String[]{url,sorturl};
    }
}